
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "Completion.h"
#include "Expression.h"
#include "Object.h"
#include "Null.h"
#include "Scope.h"
#include "WithStatement.h"

WithStatement::WithStatement(Expression* exp, Statement* stmt)
    : m_exp(exp), m_stmt(stmt)
{}

Value* WithStatement::execute_internal(Scope* scope) const
{
    // Ecma 12.10
    // 1. Evaluate expression
    // 2. Call getValue 
    // 3. Call to object
    Object* obj = m_exp->evaluate(scope)->getValue()->toObject();

    // 4. Add that to the front of the scope chain
    // TODO: what is "this"?
    Scope* nscope = new Scope(scope, obj, scope->get_this());

    // 5. Evaluate statement using the augmented scope chain
    // 6. let c be that result. If an exception was thrown in 5,
    // let c be (throw, v, empty), where v is the exception
    // TODO: should the value of the completion be c, or c's value?
    Value* c = m_stmt->execute(nscope);
    if (c->isException())
    {
        c = new Completion(CT_THROW, c, Completion::empty);
    }

    // 7. Remove result(3) from the front of the scope chain (nothing to do)
    // 8. return c
    return c;
}

void WithStatement::getDeclaredVariables(std::vector<String*>& ids) const
{
    m_stmt->getDeclaredVariables(ids);
}

